package main

import (
	"fmt"
	"log"
	"net"
	"strconv"
)

var onlineConns = make(chan net.Conn)
var messageQueue = make(chan string,1000)
var quitChan = make(chan bool)
var connections []net.Conn
var conn net.Conn
var isHttp bool

func main() {
	ln, err := net.Listen("tcp", ":80")
	if err != nil {
		panic(err)
	}
	defer func() {
		for _, connLn := range connections {
			connLn.Close()
		}
	}()
	//启动守护进程
	go ConsumeConn()
	for {
		//监听客户端请求
		connLn, e := ln.Accept()
		if e != nil {
			if ne, ok := e.(net.Error); ok && ne.Temporary() {
				log.Printf("accept temp err: %v", ne)
				continue
			}
			log.Printf("accept err: %v", e)
			return
		}
		//当有客户端请求 存入到channel当中
		onlineConns <- connLn
	}
}
//类似于守护进程监听请求
func ConsumeConn()  {
	for{
		select{
			//接收到请求之后触发 读取 任务
			case conn =<-onlineConns:
				doProcesConn(conn)
			case <-quitChan:
				break
		}
	}
}

//读取通道信息
func doProcesConn(conn net.Conn){
	defer conn.Close()
	buf := make([]byte,1024)
	for{
		numOsbytes,err := conn.Read(buf)
		if err != nil {
			break
		}
		if numOsbytes != 0 {
			message := string(buf[0:numOsbytes])
			fmt.Println(message)
			fmt.Println(string(buf))
			// 头三个字节为GET的 属于http请求 包含websocket http https http2
			if string(message[0:3]) == "GET" {
				testConn(conn)

				//models.HandleConnection(conn,message)
			}
			messageQueue <- message
		}
	}
}

//用来转化int为string
type Int int

func (i Int)toStr()string  {
	return strconv.FormatInt(int64(i),10)
}

func testConn(conn net.Conn){
	addr := conn.RemoteAddr()
	fmt.Println(addr)
	//返回的http消息体
	var respBody  = "<h1>Hello World<h1>"
	i := (Int)(len(respBody))
	fmt.Println("响应的消息体长度："+i.toStr())
	//返回的http消息头
	var respHeader  = "HTTP/1.1 200 OK\n"+
		"Content-Type: text/html;charset=ISO-8859-1\n"+
		"Content-Length: "+i.toStr()
	//拼装http返回的消息
	resp := respHeader +"\n\r\n"+ respBody
	conn.Write([]byte(resp))

}
